package integraltask

import (
	"context"
	"strconv"

	"mall/common/modelx"
	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"
	"mall/service/backend/common/utils/pointy"
	"mall/service/setting/model"
	"mall/service/setting/rpc/internal/svc"
	"mall/service/setting/rpc/internal/utils/errorhandler"
	"mall/service/setting/rpc/types/setting"

	"github.com/zeromicro/go-zero/core/logx"
)

type BackendGetIntegralTaskByIdLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBackendGetIntegralTaskByIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BackendGetIntegralTaskByIdLogic {
	return &BackendGetIntegralTaskByIdLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *BackendGetIntegralTaskByIdLogic) BackendGetIntegralTaskById(in *setting.UUIDReq) (*setting.IntegralTaskInfo, error) {
	// logx.Infof("BackendGetIntegralTaskById in : %+v", in)
	if len(in.Id) == 0 {
		return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
	}

	var res *model.SysUserIntegralTask
	if id, err := strconv.ParseInt(in.Id, 10, 64); err == nil && id > 0 {
		data, err := l.svcCtx.IntegralTask.FindOne(l.ctx, uint64(id))
		if err != nil {
			return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
		}

		res = data
	} else {
		filterMap := make(map[string]map[string][]any)
		filterMap[model.SysUserIntegralTaskColumns.RuleSlug] = map[string][]any{
			"equalTo": {in.Id},
		}
		list, _, err := l.svcCtx.IntegralTask.GetList(l.ctx, model.M{
			"pageSize": uint64(1),
			"orderBy":  model.SysUserIntegralTaskColumns.ID + " DESC",
		}, -1, filterMap)
		if err != nil {
			return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
		}

		if len(list) == 1 {
			res = list[0]
		}
	}

	if res == nil {
		return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
	}

	var desc string
	if res.Description.Valid {
		desc = res.Description.String
	}

	return &setting.IntegralTaskInfo{
		Id:            &res.ID,
		RuleName:      &res.RuleName,
		RuleSlug:      &res.RuleSlug,
		RuleType:      pointy.GetPointer(uint32(res.RuleType)),
		PicId:         &res.PicID,
		PicUrl:        &res.PicURL,
		Frequency:     pointy.GetPointer(uint32(res.Frequency)),
		Points:        &res.Points,
		EffectiveTime: pointy.GetPointer(modelx.FormatTime(res.EffectiveTime, "")),
		Ip:            &res.IP,
		Description:   pointy.GetPointer(desc),
		Sort:          pointy.GetPointer(uint32(res.Sort)),
		Status:        pointy.GetPointer(uint32(res.Status)),
		DelStatus:     pointy.GetPointer(uint32(res.DelStatus)),
		CreatedAt:     pointy.GetPointer(modelx.FormatTime(res.CreatedAt, "")),
		UpdatedAt:     pointy.GetPointer(modelx.FormatTime(res.UpdatedAt, "")),
		DeletedAt:     pointy.GetPointer(modelx.FormatNullDotTime(res.DeletedAt, "")),
	}, nil
}
